package com.servlet.user;

import com.domain.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;
import com.utils.MD5Util;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf8");
        User user = new User();
        try {
            BeanUtils.populate(user,request.getParameterMap());
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        UserService service = new UserServiceImpl();
        User selectUser = service.selectOne(user);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        // 当查询出来的对象不为null 并且 查询出来用户的密码登录 请求参数内的密码，则视为登录成功！

        if(selectUser != null && selectUser.getUpwd().equals(MD5Util.getMD5Str(user.getUpwd()+"lhdnb")) ) {
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            session.setMaxInactiveInterval(60 * 60);
            response.getWriter().write("{\"status\":0,\"message\":\"ok\"}");
        }else {
            response.getWriter().write("{\"status\":1,\"message\":\"error\"}");
        }
    }
}
